package top.ijiujiu.util;

import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 基于spring http client 实现，减少jar的引入
 *
 * @Author 神秘的黄瓜
 * @Version 1.0
 * @Date 2020-04-01 10:33
 */
public class HttpUtil {
    private RestTemplate rest;
    private HttpHeaders headers;
    private HttpStatus status;

    public HttpUtil() {
        this.rest = new RestTemplate();
        this.headers = new HttpHeaders();
    }


    public HttpUtil(String key, String value) {
        this.rest = new RestTemplate();
        this.headers = new HttpHeaders();
    }

    public String get(String uri) {
        HttpEntity<String> requestEntity = new HttpEntity<String>("", headers);
        ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.GET, requestEntity, String.class);
        this.setStatus(responseEntity.getStatusCode());
        return responseEntity.getBody();
    }

    public String post(String uri, String json) {
        HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
        ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.POST, requestEntity, String.class);
        this.setStatus(responseEntity.getStatusCode());
        return responseEntity.getBody();
    }

    public String post(String uri, MultiValueMap json) {
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(json, headers);
        ResponseEntity<String> responseEntity = rest.exchange(uri, HttpMethod.POST, requestEntity, String.class);
        this.setStatus(responseEntity.getStatusCode());
        return responseEntity.getBody();

    }

    public HttpStatus getStatus() {
        return status;
    }

    public void setStatus(HttpStatus status) {
        this.status = status;
    }

    public void postTo(String uri) throws Exception{
        HttpURLConnection url_con = null;
        URL url= new URL(uri);
        StringBuffer bankJsonBuffer = new StringBuffer();
        String jsonList ;
        //创建URL连接，提交到数据，获取返回结果
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("User-Agent","directclient");
        PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"GBK"));
        //out.println(param);
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"GBK"));
        String inputLine;
        while((inputLine = in.readLine())!=null){
            bankJsonBuffer.append(inputLine);
        }
        in.close();
        jsonList = bankJsonBuffer.toString();
    }
}